﻿using System;
using System.Windows;
using Baosight.Platform.Core;
using Baosight.ZNH.ZMCommon.ChildWindows;
using Baosight.ZNH.ZMCommon;
using Baosight.Platform.Core.UI.Controls;
using Baosight.Platform.Core.ServiceModel;
using Baosight.ZNH.ZMCommon.Validators;
using System.Windows.Controls;
using System.Collections.Generic;

namespace Baosight.ZNH.ZMCE.UI.PopWindows
{
    public partial class FaultReason : EFViewCmes
    {
        public FaultReason(string dialogType)
        {
            InitializeComponent();
            base.BeforeAction += OnBeforeAction;
            Init(dialogType);
            this.LayoutUpdated+=new EventHandler(FaultPhenomenon_LayoutUpdated);

            if ("update".Equals(dialogType) || "detail".Equals(dialogType))
            {
                this.grid.DataLoaded += new EventHandler<EventArgs>(grid_DataLoaded);
            }
        }

        /// <summary>
        /// 修改，查看明细时初始化列表数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void grid_DataLoaded(object sender, EventArgs e)
        {
            if (this.grid.HasItems)
            {
                //所有的解决方法数据
                IList<EIRow> allList = this.EIDataContext.GetBlock("popwindowResult").GetRows();

                //需要勾选中的解决方法数据
                List<string> checkList = new List<string>();
                string[] methodIds = this.EIDataContext.GetBlock("result").Get(0, "solutionMethodId").ToString().Split(',');
                foreach (string id in methodIds)
                {
                    checkList.Add(id);
                }

                for (int i = 0; i < allList.Count; i++)
                {
                    foreach (string checkId in checkList)
                    {
                        if (checkId.Equals(allList[i]["fdSystemdataId"].ToString()))
                        {
                            (this.grid.Items[i] as UIBaseEntity).IsInternalItemChecked = true;
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 过滤指定类型的标准设备
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FaultPhenomenon_LayoutUpdated(object sender, EventArgs e)
        {
            equipment.eViewInitParams = "bindingService=ZM06.queryStandardEquipment,columns=fdName|fdSpecifications|fdModel,queryConditions=fdName,initParam=fdToencode:" + this.fdClassToencode.Value;
        }

        /// <summary>
        /// 初始化父类EFViewCmesProperty的值，每次点击“确定”、“返回”时执行此方法，从新赋值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnBeforeAction(object sender, EventArgs e)
        {
            EFViewCmesProperty _view = new EFViewCmesProperty();
            _view.DataFields = this.spWindows.GetChildObjects<EFDataField>(null, true);
            base.ViewProperty = _view;
        }

        /// <summary>
        /// 初始化页面数据
        /// </summary>
        private void Init(string type)
        {
            type = type == null ? "insert" : type.ToLower();

            switch (type)
            {
                case "insert":
                    base.Mode = OperationMode.Insert;
                    break;
                case "update":
                    base.Mode = OperationMode.Update;
                    break;
                case "detail":
                    this.Commit.Visibility = Visibility.Collapsed;
                    this.grid.IsEnabled = false;
                    BaseTools.EFDataFieldNotEnabled(this.spWindows.GetChildObjects<EFDataField>(null, true));
                    break;
                default:
                    break;
            }

        }

        /// <summary>
        /// 确定按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CommitClick(object sender, RoutedEventArgs e)
        {
            //按钮不可用，防止双击
            Button button = sender as Button;
            button.IsEnabled = false;
            TempButton = button;

            if (BeforeAction != null)
            {
                BeforeAction.Invoke(null, null);
            }

            //ValidatorManager自定义的校验方法
            bool result = true;
            ValidatorManager group = this.GetChildObject<ValidatorManager>(null);
            if (group != null)
            {
                result = group.IsValidSucces;
            }

            bool _validateField = ThisValidateField() & this.ValidateField() & result;//确定前的效验

            if (!_validateField)
            {
                this.ValidateMessagePopup();//弹出提示信息
                this.TempButtonOpen(true);//确定按钮生效
            }
            else
            {
                int count = this.grid.GetCheckedEIRows().Count;
                if (count <= 0)
                {
                    this.OpenEFWindowAlert("请选择解决方法！", true);
                    return;
                }
                else 
                {
                    EIInfo eiInfo = new EIInfo();
                    eiInfo.Set("service", this.eServiceName);
                    eiInfo.Set("method", Mode.ToString().ToLower());

                    //主数据区新增block
                    this.BaseBlock(eiInfo);

                    //列表新增block
                    this.SubBlock(eiInfo);

                    HttpServiceAgent agent = new HttpServiceAgent();
                    agent.CallService(eiInfo, OnDoCommitCompleted);
                }
            }
        }

        /// <summary>
        /// 弹出的新增、修改页面点击"确定"后的回调
        /// 具体实现内中可以重构
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnDoCommitCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            EIInfo inInfo = e.EIInfo;
            if (inInfo.Status == -1)
            {
                this.TempButtonOpen(true);
                this.OnCommitMessagePopup(inInfo);//操作失败，消息提醒
            }
            else
            {
                //操作成功关闭新增页面
                //此处可以扩展是否连续新增
                EFWindow window = this.Parent as EFWindow;
                window.DialogResult = true;
                window.Close();
            }
        }

        /// <summary>
        /// 取消按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CancelClick(object sender, RoutedEventArgs e)
        {
            CmesWindows _window = this.Parent as CmesWindows;
            _window.DialogResult = false;
            _window.Close();
        }

        /// <summary>
        /// 带出标准设备信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void fdEquipmentId_ValueChanged(object sender, ValueChangedEventArgs e)
        {
            if (e.NewValue == null && e.OldValue.Equals(""))
            {
                return;
            }

            EFDataField field = sender as EFDataField;
            CmesCustomView picker = field.Content as CmesCustomView;

            if (picker.ItemObject != null)
            {
                if (!picker.ItemObject.Equals(""))
                {
                    this.fdToencode.Value = picker.ItemObject.GetType().GetProperty("fdToencode").GetValue(picker.ItemObject, null) as string;
                    this.fdEquipmentSpecifications.Value = picker.ItemObject.GetType().GetProperty("fdSpecifications").GetValue(picker.ItemObject, null) as string;
                    this.fdEquipmentModel.Value = picker.ItemObject.GetType().GetProperty("fdModel").GetValue(picker.ItemObject, null) as string;
                }
                //没选中时赋予空字符串
                else
                {
                    this.fdToencode.Value = "";
                    this.fdEquipmentSpecifications.Value = "";
                    this.fdEquipmentModel.Value = "";
                }
            }
        }

        /// <summary>
        /// 将新增页面中的录入信息组织成一个block
        /// </summary>
        /// <param name="eiInfo"></param>
        private void BaseBlock(EIInfo eiInfo)
        {
            EIBlock baseBlock = new EIBlock("result");
            EIColumn column = new EIColumn();
            column.SetName("fdKeyId");
            baseBlock.AddColumn(column);

            column = new EIColumn();
            column.SetName("fdToencode");
            baseBlock.AddColumn(column);

            column = new EIColumn();
            column.SetName("fdCode");
            baseBlock.AddColumn(column);

            column = new EIColumn();
            column.SetName("fdStandredequipmentId");
            baseBlock.AddColumn(column);

            column = new EIColumn();
            column.SetName("fdDescription");
            baseBlock.AddColumn(column);

            EIRow baseRow = new EIRow();
            baseRow.Add("fdKeyId", this.fdKeyId.Value);
            baseRow.Add("fdToencode", this.fdToencode.Value);
            baseRow.Add("fdCode", this.fdCode.Value);
            baseRow.Add("fdStandredequipmentId", this.fdStandredequipmentId.Value);
            baseRow.Add("fdDescription", this.fdDescription.Value);
           
            baseBlock.AddRow(baseRow);
            eiInfo.AddBlock(baseBlock);
        }

        /// <summary>
        /// 将列表中选中记录组织成一个block
        /// </summary>
        /// <param name="eiInfo"></param>
        private void SubBlock(EIInfo eiInfo)
        {
            EIBlock subBlock = new EIBlock("popwindowResult");
            subBlock.SetColumns(this.grid.EIBlock.GetColumns());
            subBlock.SetRows(this.grid.GetCheckedEIRows());
            eiInfo.AddBlock(subBlock);
        }
    }
}
